import React, { Component } from 'react'
import PropTypes from 'prop-types';
import {scaleLinear,scaleBand} from 'd3-scale';
import * as d3 from 'd3';

const getXScale=(data,width,height,margin)=>{
  return scaleBand().domain(d3.range(data.length)).range([margin.left,width-margin.right])

}


const getYScale=(data,width,height,margin)=>{
  return scaleLinear().domain([0,d3.max(data)]).range([height-margin.bottom,margin.top])

}
export default class BarChart extends Component {
  static propTypes={
    width:PropTypes.number,
    height:PropTypes.number,
    data:PropTypes.arrayOf(PropTypes.number),
    margin:PropTypes.shape({
      top:PropTypes.number,
      right:PropTypes.number,
      bottom:PropTypes.number,
      left:PropTypes.number
    })
  }

  static defaultProps={
    data:[],
    width:200,
    height:100,
    margin:{top:0,right:0,bottom:0,left:0}
  }

  componentDidMount(){
    const {width,height,data,margin,fillColor}=this.props;
    const xScale=getXScale(data,width,height,margin);
    const yScale=getYScale(data,width,height,margin);
    const yRange=yScale.range();
    const container=this.refs.container;
    const chart=d3.select(container)
    .append('svg')
    .attr('width',width)
    .attr('height',height);
    const barWidth=xScale.bandwidth();
    const bars=chart.selectAll('.bar').data(data);

    bars.enter().append('g').classed('.bar',true).attr('transform',(d,i)=>`translate(${margin.left + i*barWidth},0)`).append('rect').attr('y',d=>yScale(d)).attr('height',d=>yRange[0]-yScale(d)).attr('width',d=>barWidth-1).attr('fill',fillColor)
  }
  render() {
    return (
      <div className="bar-chart" ref="container">
       
      </div>
    )
  }
}
